const router=require('koa-router')()
const sequelize=require('../config/db')
const uuidv1 = require('uuid/v1')
const statusCode=require('../util/status-code')

const Links=sequelize.import('../schema/links')
const Userinfo=sequelize.import('../schema/userinfo')
const Project=sequelize.import('../schema/project')

Userinfo.sync({force:false})
Links.sync({force:false})

router.prefix('/api/v1/resume')

router.get('/userinfo/list',async (ctx,next)=>{
  try {
    const userinfo=await Userinfo.findAll({
      attributes:{
        // exclude:['createdAt', 'updatedAt']
      }
    })
    ctx.body=statusCode.s200(userinfo)
  }catch (e) {

  }
})



router.post('/userinfo/create',async (ctx,next)=>{
  let body=ctx.request.body
  let uuid=uuidv1()
  body.uuid=uuid
  try {
    await Userinfo.create(body)
    const {links=[]}=body
    await links.forEach(async item=>{
      await Links.create({
        ...item,
        uuid
      })
    })
    ctx.body=statusCode.s200(body)
  }catch (e) {
    console.log(e)
    ctx.body=statusCode.e412(e)
  }
})

router.put('/userinfo/update/:id',async (ctx,next)=>{
  let body=ctx.request.body
  let uuid=ctx.params.id
  await Userinfo.update(body,{
    where:{
      uuid
    }
  })
  await Links.destroy({
    where:{
      uuid
    }
  })
  const {links}=body
  await links.forEach(async item=>{
    await Links.create({
      ...item,
      uuid
    })
  })
  // console.log(links)
  ctx.body=statusCode.s200(body)
})

router.delete('/userinfo/del/:id',async (ctx)=>{
  let uuid=ctx.params.id
  try {
    await Userinfo.destroy({
      where:{uuid}
    })
    await Links.destroy({
      where:{uuid}
    })
    await Project.destroy({
      where:{uuid}
    })
    ctx.body=statusCode.s200(uuid)
  }catch (e) {

  }
})

module.exports = router